package com.example.admin.mywebview;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.webkit.WebSettings;
import android.webkit.WebView;

import com.yanzhenjie.album.Album;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private static final int PHOTO_REQUEST_CUT = 2;
    private OpenFileWebChromeClient mOpenFileWebChromeClient = new OpenFileWebChromeClient(this);
    private Uri uritempFile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        WebView webView = findViewById(R.id.webview);
        webView.setWebChromeClient(mOpenFileWebChromeClient);
        WebSettings ws = webView.getSettings();
        ws.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        ws.setJavaScriptCanOpenWindowsAutomatically(false);//设置js可以直接打开窗口，如window.open()，默认为false
        ws.setJavaScriptEnabled(true);//是否允许执行js，默认为false。设置true时，会提醒可能造成XSS漏洞
        ws.setAllowFileAccess(true);//设置可访问文件
        ws.setSupportZoom(true);//是否可以缩放，默认true
        ws.setBuiltInZoomControls(false);//是否显示缩放按钮，默认false
        ws.setUseWideViewPort(true);//设置此属性，可任意比例缩放。大视图模式
        ws.setLoadWithOverviewMode(true);//和setUseWideViewPort(true)一起解决网页自适应问题
        ws.setAppCacheEnabled(true);//是否使用缓存
        ws.setCacheMode(WebSettings.LOAD_NO_CACHE);
        ws.setDomStorageEnabled(true);//DOM Storage
        webView.loadUrl("http://192.168.1.128/test/index.html");

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        if (requestCode == OpenFileWebChromeClient.REQUEST_FILE_PICKER) {
//            startPhotoZoom(data.getData());
//        }
        if (requestCode == 1) {
            //单文件选择
            if (mOpenFileWebChromeClient.mFilePathCallback != null) {
                Uri result = data.getData();
                if (result != null) {
                    String path = MediaUtility.getPath(getApplicationContext(), result);
                    Uri uri = Uri.fromFile(new File(path));
                    mOpenFileWebChromeClient.mFilePathCallback.onReceiveValue(uri);
                } else {
                    mOpenFileWebChromeClient.mFilePathCallback.onReceiveValue(null);
                }
            }
            //多文件选择
            if (mOpenFileWebChromeClient.mFilePathCallbacks != null) {
                List<String> pathList = Album.parseResult(data);
                if (pathList.size() > 0) {
                    Uri[] uris = new Uri[pathList.size()];
                    int i = 0;
                    for (String item : pathList) {
                        uris[i] = Uri.fromFile(new File(item));
                        i++;
                    }
                    mOpenFileWebChromeClient.mFilePathCallbacks.onReceiveValue(uris);
                } else {
                    mOpenFileWebChromeClient.mFilePathCallbacks.onReceiveValue(null);
                }
            }
            mOpenFileWebChromeClient.mFilePathCallback = null;
            mOpenFileWebChromeClient.mFilePathCallbacks = null;
        }


    }

    //图片裁剪
    private void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // crop为true是设置在开启的intent中设置显示的view可以剪裁
        intent.putExtra("crop", "true");

        // aspectX aspectY 是宽高的比例

        //不设置1:1是因为部分手机需特殊处理 不然会显示圆如：（华为）
        intent.putExtra("aspectX", 9998);
        intent.putExtra("aspectY", 9999);


        // outputX,outputY 是剪裁图片的宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        /*
         * 此方法返回的图片只能是小图片（sumsang测试为高宽160px的图片）
         * 故只保存图片Uri，调用时将Uri转换为Bitmap，此方法还可解决miui系统不能return data的问题
         */
        //intent.putExtra("return-data", true);

        //裁剪后的图片Uri路径，uritempFile为Uri类变量
        SimpleDateFormat forma = new SimpleDateFormat("yyyyMMdd_HHmmss", java.util.Locale.getDefault());
        String timeStamp = forma.format(new Date());
        String savepath = Environment.getExternalStorageDirectory().getPath() + "/upload_" + timeStamp + ".jpg";
        uritempFile = Uri.parse("file:///" + savepath);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uritempFile);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        startActivityForResult(intent, PHOTO_REQUEST_CUT);
    }

}
